package router

import (
	"gfrest/common/web_middleware"
	"gfrest/common/web_middleware/prom"
	"gfrest/web/app/api"

	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	metrics "github.com/slok/go-http-metrics/metrics/prometheus"
	"github.com/slok/go-http-metrics/middleware"
)

// 统一路由注册.
func init() {
	s := g.Server()
	// Create our middleware.
	mdlw := middleware.New(middleware.Config{
		Recorder: metrics.NewRecorder(metrics.Config{}),
	})
	s.BindHandler("/", func(r *ghttp.Request) {
		r.Response.Write("哈喽世界！")
	})
	s.BindMiddleware("/*", prom.Handler("", mdlw))

	s.BindMiddleware("/*", web_middleware.CorsMiddleware)
	s.BindMiddleware("/*", web_middleware.ReqIDMiddleware)
	// s.BindHandler("/login.html", index_api.Index)
	s.BindHandler("POST:/login", web_middleware.GfJWTMiddleware.LoginHandler)

	s.Group("/misc", func(g *ghttp.RouterGroup) {
		g.GET("/", new(api.MiscController))
		g.GET("/", new(api.MonitorServer))
	})

	s.Group("/auth", func(g *ghttp.RouterGroup) {
		g.Middleware(web_middleware.MiddlewareAuth)
		g.GET("/refresh", web_middleware.GfJWTMiddleware.RefreshHandler)
		g.ALL("/", new(api.AuthController))
	})
	s.Group("/admin", func(g *ghttp.RouterGroup) {
		g.Middleware(web_middleware.MiddlewareAuth)
		g.ALL("/vm_info", new(api.VmInfoController))
		g.ALL("/auth_group", new(api.AuthGroupController))
		g.ALL("/auth_user", new(api.AuthUserController))

	})

	s.BindHookHandlerByMap("/*", map[string]ghttp.HandlerFunc{
		ghttp.HOOK_AFTER_SERVE: web_middleware.CleanUpMiddleware,
	})

	s.BindHandler("/metrics", func(r *ghttp.Request) {
		a := promhttp.Handler()
		a.ServeHTTP(r.Response.ResponseWriter.RawWriter(), r.Request)
	})

}
